package mymac.com.test_3_1;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Objects;

/**
 * Created by mymac on 2017/2/26.
 */

public class DepsFragment extends Fragment {
    private SharedPreferences preferences;
    private ListView listView;
    private MyAdapter adapter = new MyAdapter();
    private ArrayList<DepsItem> datas = new ArrayList<>();
    private Button btn_add;
    private String token;
    private AlertDialog builder;
    int i = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_deps, null);
        listView = (ListView) view.findViewById(R.id.lv_deps);
        btn_add = (Button) view.findViewById(R.id.btn_add);
        preferences = getActivity().getSharedPreferences("token", Activity.MODE_PRIVATE);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setOnclick();
        token = preferences.getString("token", "");
        this.registerForContextMenu(listView);
    }

    @Override
    public void onResume() {
        super.onResume();
        datas.clear();
        loadData();
    }

    //新建
    private void setOnclick() {
        btn_add.setOnClickListener(new MyOnClickListener());
    }

    class MyOnClickListener implements OnClickListener {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getActivity(), AddDepsActivity.class);
            startActivity(intent);
        }
    }

    //加载数据
    public void loadData() {
        datas.clear();
        final String address = "http://a.xl18z.cn/api/department/list?token=" + token;
        HttpActivity.getInstance().getJson(address, new DataCallBack() {
            @Override
            public void onErr(Object object) {
                JSONObject json = (JSONObject) object;
                try {
                    JSONArray recordArr = json.getJSONArray("record");
                    for (int i = 0; i < recordArr.length(); i++) {
                        JSONObject temp = (JSONObject) recordArr.get(i);
                        String id = temp.optString("id");
                        String name = temp.optString("name");
                        DepsItem data = new DepsItem();
                        data.id = id;
                        data.name = name;

                        datas.add(data);
                        listView.setAdapter(adapter);
                        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                view.showContextMenu();
                                listView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
                                    @Override
                                    public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
                                        contextMenu.add(0, 0, 0, "修改");
                                        contextMenu.add(0, 1, 0, "删除");
                                    }
                                });
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    // 菜单响应函数
    public boolean onContextItemSelected(MenuItem item) {
        final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        switch (item.getItemId()) {
            // 修改操作
            case 0:
                modification(info);
                break;
            //删除操作
            case 1:
                delete(info);
                break;
        }
        return super.onContextItemSelected(item);
    }


    //删除item
    private void delete(AdapterView.AdapterContextMenuInfo info) {
        String id = ((TextView) info.targetView.findViewById(R.id.tv_deps_id)).getText().toString();
        String address = "http://a.xl18z.cn/api/department/del?id=" + id + "&token=" + token;
        HttpActivity.getInstance().getErrMsg(address, new DataCallBack() {
            @Override
            public void onErr(Object object) {
                String errmsg = (String) object;
                if ("ok!".equals(errmsg)) {
                    loadData();
                    datas.clear();
                    Toast.makeText(getActivity(), "删除成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity(), "删除失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    //修改item
    private void modification(AdapterView.AdapterContextMenuInfo info) {
        final String id = ((TextView) info.targetView.findViewById(R.id.tv_deps_id)).getText().toString();
        final String name = ((TextView) info.targetView.findViewById(R.id.tv_deps_name)).getText().toString();

        ShowView.getInstance().showView(getActivity(), R.layout.activity_popmodification, new ShowCallBack() {
            @Override
            public void showBuiler(Object obj1, Object obj2) {
                Window window = (Window) obj1;
                builder = (AlertDialog) obj2;
                final EditText et_name = (EditText) window.findViewById(R.id.et_modName);
                et_name.setHint(name);
                Button btn_mod = (Button) window.findViewById(R.id.btn_mod);
                btn_mod.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String name = et_name.getText().toString().trim();
                        String address = "http://a.xl18z.cn/api/department/update?token=" + token + "&id=" + id + "&name=" + name;
                        HttpActivity.getInstance().getErrMsg(address, new DataCallBack() {
                            @Override
                            public void onErr(Object object) {
                                String errmsg = (String) object;
                                if ("ok!".equals(errmsg)) {
                                    loadData();
                                    datas.clear();
                                    builderCancel(builder, errmsg);
                                } else {
                                    builderCancel(builder, errmsg);
                                }
                            }
                        });
                    }
                });
            }
        });
    }

    public void builderCancel(AlertDialog builder, String errmsg) {
        builder.cancel();
        Toast.makeText(getActivity(), "" + errmsg, Toast.LENGTH_SHORT).show();
    }

    //适配器
    class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            View contentView;
            if (view == null) {
                contentView = View.inflate(getActivity().getApplicationContext(), R.layout.activity_deps_item, null);
            } else {
                contentView = view;
            }
            TextView id = (TextView) contentView.findViewById(R.id.tv_deps_id);
            TextView name = (TextView) contentView.findViewById(R.id.tv_deps_name);
            id.setText(datas.get(i).getId());
            name.setText(datas.get(i).getName());
            return contentView;
        }
    }
}
